<?php
/**
 * adapter.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2018/09/08
 * Time: 23:19
 */

/**
 * 需求：我们有一个 MediaPlayer 接口和一个实现了 MediaPlayer 接口的实体类 AudioPlayer。
 * 默认情况下，AudioPlayer 可以播放 mp3 格式的音频文件。
 * 我们还有另一个接口 AdvancedMediaPlayer 和实现了 AdvancedMediaPlayer 接口的实体类。
 * 该类可以播放 vlc 和 mp4 格式的文件。
 * 我们想要让 AudioPlayer 播放其他格式的音频文件。
 * 为了实现这个功能，我们需要创建一个实现了 MediaPlayer 接口的适配器类 MediaAdapter，并使用 AdvancedMediaPlayer 对象来播放所需的格式。
 * AudioPlayer 使用适配器类 MediaAdapter 传递所需的音频类型，不需要知道能播放所需格式音频的实际类。
 * AdapterPatternDemo，我们的演示类使用 AudioPlayer 类来播放各种格式
 */
interface MediaPlayer {
    public function play($audioType,$fileName);
}

interface AdvancedMediaPlayer {
    public function playVlc($fileName);
    public function playMp4($fileName);
}

class VlcPlayer implements AdvancedMediaPlayer {
    # Override
    public function playVlc($fileName)
    {
        // TODO: Implement playVlc() method.
        echo("Playing vlc file. Name: ".$fileName."\n");
    }
    # Override
    public function playMp4($fileName)
    {
        // 什么也不做
    }
}

class Mp4Player implements AdvancedMediaPlayer {
    # Override
    public function playVlc($fileName)
    {
        // 什么也不做
    }
    # Override
    public function playMp4($fileName)
    {
        // TODO: Implement playVlc() method.
        echo("Playing mp4 file. Name: ".$fileName."\n");
    }
}

class MediaAdapter implements MediaPlayer {
    public $advancedMusicPlayer = null;

    public function __construct($audioType='')
    {
        $this->advancedMusicPlayer = new $audioType();
    }

    public function play($audioType, $fileName)
    {
        // TODO: Implement play() method.
        $this->advancedMusicPlayer->$audioType($fileName);
    }
}

class AudioPlayer implements MediaPlayer {
    public $mediaAdapter = null;
    public function play($audioType, $fileName)
    {
        // TODO: Implement play() method.
        if($audioType == 'mp3'){
            echo("Playing mp3 file. Name: ".$fileName."\n");
        }else if($audioType == 'vlc'){
            $this->mediaAdapter = new MediaAdapter('VlcPlayer');
            $this->mediaAdapter->play('playVlc',$fileName);
        }else if($audioType == 'mp4'){
            $this->mediaAdapter = new MediaAdapter('Mp4Player');
            $this->mediaAdapter->play('playMp4',$fileName);
        }else{
            echo("Invalid media. ".$audioType." format not supported\n");
        }
    }
}


// 测试
$audioPlayer = new AudioPlayer();
$audioPlayer->play("mp3", "beyond the horizon.mp3");
$audioPlayer->play("mp4", "alone.mp4");
$audioPlayer->play("vlc", "far far away.vlc");
$audioPlayer->play("avi", "mind me.avi");









